<?php

// [ api统一入口 ]
// [模块.]资源.操作

namespace app\api\controller;
use think\Request;
use think\facade\Hook;
use app\api\lib\Response;

class Index
{
    // 允许请求的方法
    private $_allowRequestMethod = ['GET','POST','PUT','DELETE','OPTIONS'];

    public function index(Request $request)
    {
        // 允许跨域访问
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS");

        $method = $request->method();
        in_array($method, $this->_allowRequestMethod) || Response::send(405,'请求方法不被允许[1]');
        
        $url = $request->url();
        $pattern = strpos($url,'&') ? '/\?(.*)&/U' : '/\?(.*)/';
        preg_match($pattern,$url,$matches) || Response::send(400,'请求资源不合法[1]');
        $arr = preg_split('/\./',$matches[1]);
        empty($arr[0]) && Response::send(400,'请求资源不合法[2]');
        $count = count($arr) - 1;
        $file  = "app\\api\\resource";
        foreach($arr as $key => $val) {
            empty($val) && Response::send(400,'请求资源不合法[3]');
            $val   = ($key == $count) ? ucfirst($val) : strtolower($val);
            $file .= "\\" . $val;
        }

        $alias = str_replace('\\',DS,$file);
        is_file(ROOT_PATH . $alias . '.php') || Response::send(404,'请求资源不存在[1]');
        $class = new $file;
        
        isset($class->_method['OPTIONS']) || $class->_method[] = 'OPTIONS';
        empty($class->_method) || ( in_array($method, $class->_method) || Response::send(405,'请求方法不被允许[2]') );

        // api请求前监听
        Hook::listen('api_request_before',[$request,$class]);

        $result = call_user_func_array([$class,'run'],[&$request]);

        // api请求后监听
        Hook::listen('api_request_after',[$request,$result]);

        is_numeric($result) && Response::send($result);
        is_array($result)   && Response::send($result[0],$result[1]);
        Response::send(500);
    }
}